package com.regulareport.form.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

import com.regulareport.common.core.domain.entity.ReportFormsEdit;
import com.regulareport.common.exception.ServiceException;
import com.regulareport.common.utils.StringUtils;
import com.regulareport.common.utils.bean.BeanValidators;
import com.regulareport.form.domain.ReportVerificationConfig;
import com.regulareport.form.mapper.ReportFormsEditMapper;
import com.regulareport.form.mapper.ReportVerificationConfigMapper;
import com.regulareport.form.service.IReportVerificationConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;

/**
 * 校验配置Service业务层处理
 * 
 * @author
 * @date 2025-10-08
 */
@Service
public class ReportVerificationConfigServiceImpl implements IReportVerificationConfigService
{
    private static final Logger log = LoggerFactory.getLogger(ReportVerificationConfigServiceImpl.class);

    @Autowired
    private ReportVerificationConfigMapper reportVerificationConfigMapper;

    @Autowired
    private ReportFormsEditMapper reportFormsEditMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询校验配置
     * 
     * @param pkId 校验配置主键
     * @return 校验配置
     */
    @Override
    public ReportVerificationConfig selectReportVerificationConfigByPkId(Long pkId)
    {
        return reportVerificationConfigMapper.selectReportVerificationConfigByPkId(pkId);
    }

    /**
     * 查询校验配置列表
     * 
     * @param reportVerificationConfig 校验配置
     * @return 校验配置
     */
    @Override
    public List<ReportVerificationConfig> selectReportVerificationConfigList(ReportVerificationConfig reportVerificationConfig)
    {
        List<ReportVerificationConfig> reportVerificationConfigList = reportVerificationConfigMapper.selectReportVerificationConfigList(reportVerificationConfig);
        for(ReportVerificationConfig reportVerConfig : reportVerificationConfigList){

        }
        return reportVerificationConfigList;
    }

    /**
     * 新增校验配置
     * 
     * @param reportVerificationConfig 校验配置
     * @return 结果
     */
    @Override
    public int insertReportVerificationConfig(ReportVerificationConfig reportVerificationConfig)
    {
//        reportVerificationConfig.setCreateTime(DateUtils.getNowDate());
        return reportVerificationConfigMapper.insertReportVerificationConfig(reportVerificationConfig);
    }

    /**
     * 修改校验配置
     * 
     * @param reportVerificationConfig 校验配置
     * @return 结果
     */
    @Override
    public int updateReportVerificationConfig(ReportVerificationConfig reportVerificationConfig)
    {
//        reportVerificationConfig.setUpdateTime(DateUtils.getNowDate());
        return reportVerificationConfigMapper.updateReportVerificationConfig(reportVerificationConfig);
    }

    /**
     * 批量删除校验配置
     * 
     * @param pkIds 需要删除的校验配置主键
     * @return 结果
     */
    @Override
    public int deleteReportVerificationConfigByPkIds(Long[] pkIds)
    {
        return reportVerificationConfigMapper.deleteReportVerificationConfigByPkIds(pkIds);
    }

    /**
     * 删除校验配置信息
     * 
     * @param pkId 校验配置主键
     * @return 结果
     */
    @Override
    public int deleteReportVerificationConfigByPkId(Long pkId)
    {
        return reportVerificationConfigMapper.deleteReportVerificationConfigByPkId(pkId);
    }

    /**
     * 导入校验配置数据
     *
     * @param verificationConfigList 校验配置数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importVerificationConfig(List<ReportVerificationConfig> verificationConfigList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(verificationConfigList) || verificationConfigList.size() == 0)
        {
            throw new ServiceException("导入校验数据不能为空！");
        }
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ReportVerificationConfig verificationConfig : verificationConfigList)
        {
            String editionStr = "";
            try
            {
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                editionStr = outputFormat.format(verificationConfig.getEdition());
                ReportVerificationConfig verifyConfigParams = new ReportVerificationConfig();
                verifyConfigParams.setIndexNo(verificationConfig.getIndexNo());
                verifyConfigParams.setVerificationFormula(verificationConfig.getVerificationFormula());
                verifyConfigParams.setEdition(verificationConfig.getEdition());
                if(StringUtils.isNotEmpty(verificationConfig.getOrgScope())){
                    verificationConfig.setOrgScope(verificationConfig.getOrgScope().replaceAll("、", ","));
                }
                // 验证是否存在这个用户
                List<ReportVerificationConfig> verificationConfigs = reportVerificationConfigMapper.selectReportVerificationConfigList(verifyConfigParams);
                if (!CollectionUtils.isEmpty(verificationConfigs))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + "、指标编号： " + verificationConfig.getIndexNo() +" , 版本日期： "+ editionStr +" , 公式： "+ verificationConfig.getVerificationFormula() + " , 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + ", 指标编号： " + verificationConfig.getIndexNo() +" , 版本日期： "+ editionStr + " , 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }

        for (ReportVerificationConfig verificationConfig : verificationConfigList) {
            if(StringUtils.isNotEmpty(verificationConfig.getOrgScope())){
                verificationConfig.setOrgScope(verificationConfig.getOrgScope().replaceAll("、", ","));
            }
            ReportFormsEdit repFormsEdit = reportFormsEditMapper.selectReportFormsEditLatest(verificationConfig.getReportFormNo());
            if(repFormsEdit != null){
                Long reportFormID = repFormsEdit.getPkId();
                verificationConfig.setReportFormId(reportFormID);
            }
            BeanValidators.validateWithException(validator, verificationConfig);
            verificationConfig.setCreateBy(operName);
            if(StringUtils.isNotEmpty(verificationConfig.getReportFormNoSon())){
                ReportFormsEdit repFormsEditSon = reportFormsEditMapper.selectReportFormsEditLatest(verificationConfig.getReportFormNoSon());
                if(repFormsEditSon != null) {
                    verificationConfig.setReportFormIdSon(repFormsEditSon.getPkId());
                }
            }
            verificationConfig.setDelFlag("0"); //默认非删除状态
//            successMsg.append("<br/>" + successNum + "、指标编号： " + verificationConfig.getIndexNo() +" , 版本日期： "+ verificationConfig.getEdition() + " , 导入成功");
        }

        int resultInt = reportVerificationConfigMapper.batchInsertReportVerificationConfig(verificationConfigList);
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + resultInt + " 条，数据如下：");

        return successMsg.toString();
    }

    @Override
    public String verifyFigures(String reportFormIds) {
        String[] reportFormIdArr = reportFormIds.split(",");

        if(reportFormIdArr == null){
            return null;
        }

        List<ReportVerificationConfig> reportVerificationConfigList = reportVerificationConfigMapper.selectVerificationConfigListByPkIds(
                Arrays.stream(reportFormIdArr).map(Long::valueOf)
                .toArray(Long[]::new));

        return "";
    }

}
